import 'package:flutter/material.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/entities/message_page_entity.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MessageDetailPage extends StatefulWidget {
  final String messageId;
  final String title;

  const MessageDetailPage({super.key, required this.messageId, required this.title});

  @override
  State<MessageDetailPage> createState() => _MessageDetailPageState();
}

class _MessageDetailPageState extends State<MessageDetailPage> {
  _buildMainView() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: mainAppBar(title: "消息详情"),
      body: FutureBuilder(
        future: _fetchMessageDetail(),
        builder: (context, snapshot) {
          // 请求已结束
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              // 请求失败，显示错误
              return Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.center,
                child: const Text("消息详情获取失败"),
              );
            } else {
              MessageInfo messageInfo = snapshot.data as MessageInfo;
              // 请求成功，显示数据
              return Column(
                children: [
                  Container(width: double.infinity, height: 20.h, color: AppConstants.pageBackgroundColor),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 25.w, vertical: 20.h),
                      child: ListView(children: [
                        Center(child: Text(widget.title, style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w600))),
                        SizedBox(height: 8.h),
                        Center(child: Text("发布时间: ${messageInfo.createTime}", style: TextStyle(fontSize: 22.sp, fontWeight: FontWeight.w500))),
                        SizedBox(height: 8.h),
                        Text.rich(TextSpan(text: messageInfo.msgContent, style: const TextStyle(color: Color(0xFF747474)))),
                        SizedBox(height: 20.h),
                      ]),
                    ),
                  ),
                ],
              );
            }
          } else {
            // 请求未结束，显示loading
            return Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              child: const CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  _fetchMessageDetail() async {
    var messageInfo = await AppApi.getMessageDetail(msgId: widget.messageId);
    AppApi.readMessage(msgId: widget.messageId);
    return Future(() => messageInfo);
  }
}
